import React, { useState, useEffect } from "react";
import { Upload, Button, message, Modal } from "antd"
import { PlusOutlined } from '@ant-design/icons';
import { reomte_host } from "../../../config";

const file_server = "/api/predict"

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

function InputImage(props) {
    //props
    const { passOutput } = props
    console.log(passOutput)
    //states
    const [filelist, setFilelist] = useState([])
    const [previewVisible, setPreviewVisible] = useState(false)
    const [previewTitle, setPreviewTitle] = useState('')
    const [previewImage, setPreviewImage] = useState('')
    const [imageUrl, setImageUrl] = useState('');

    useEffect(() => {
        passOutput(imageUrl)
    }, [imageUrl])

    const handleChange = ({ fileList, file }) => {
        console.log(file.response)
        if (file.response) {
            const { output } = file.response
            const url = reomte_host + output

            setImageUrl(url)
        }
        setFilelist(fileList)
    };

    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        if (file.response) {
            const { output } = file.response
            const url = reomte_host + output

            setImageUrl(url)
        }
        setPreviewVisible(true)
        setPreviewImage(file.preview)
        setPreviewTitle(file.name)
    }

    const handleCancel = () => {
        setPreviewVisible(false)
    }

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    return (
        <div className="upload-area">
            <Upload
                action={file_server}
                listType="picture-card"
                fileList={filelist}
                onChange={handleChange}
                onPreview={handlePreview}
            >
                {uploadButton}
            </Upload>
            <Modal
                visible={previewVisible}
                title={previewTitle}
                footer={null}
                onCancel={handleCancel}
            >
                <img alt="example" style={{ width: '100%' }} src={previewImage} />

            </Modal>
        </div>
    )
}

export default InputImage;